package com.seafood.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成工具类
 */
@Component
public class QRCodeUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);
    
    @Value("${app.qrcode.base-url}")
    private String baseUrl;
    
    /**
     * 生成二维码内容
     */
    public String generateQRContent(String batchNumber) {
        return baseUrl + batchNumber;
    }
    
    /**
     * 生成二维码图片字节数组
     */
    public byte[] generateQRCodeImage(String content, int width, int height) {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            
            // 设置编码参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1);
            
            // 生成二维码矩阵
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            
            // 将矩阵转换为图片字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
            
            return outputStream.toByteArray();
            
        } catch (WriterException | IOException e) {
            logger.error("生成二维码失败: {}", e.getMessage());
            throw new RuntimeException("生成二维码失败", e);
        }
    }
    
    /**
     * 生成标准尺寸的二维码
     */
    public byte[] generateQRCodeImage(String content) {
        return generateQRCodeImage(content, 200, 200);
    }
    
    /**
     * 为批次号生成二维码
     */
    public byte[] generateQRCodeForBatch(String batchNumber) {
        String content = generateQRContent(batchNumber);
        return generateQRCodeImage(content);
    }
}